package io.github.xxyopen.novel.core.common.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
public class OSSUploadUtil {

    // 配置参数（建议从配置文件中读取）
    //https://blueben.oss-cn-beijing.aliyuncs.com

    @Autowired
    AliyunOssProperties aliyunOssProperties;

    // 上传图片方法
    public String uploadFile(String objectName, InputStream inputStream) {
        String endpoint = aliyunOssProperties.getEndpoint();
        String accessKeyId = aliyunOssProperties.getAccessKeyId();
        String accessKeySecret = aliyunOssProperties.getAccessKeySecret();
        String bucketName = aliyunOssProperties.getBucketName();

        System.out.println(aliyunOssProperties);
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建上传请求
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, objectName, inputStream);
            // 执行上传
            ossClient.putObject(putObjectRequest);

            // 返回访问URL（图片上传后的公开访问地址）
            return "https://" + bucketName + "." + endpoint.substring(endpoint.lastIndexOf("/") + 1) + "/" + objectName;

        } catch (OSSException oe) {
            System.out.println("OSS Exception: " + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("Client Exception: " + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}